﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
using System;

namespace MDT.LifeSewagePlatform.Conmmon
{
    public class CustomExceptionFilter : ExceptionFilterAttribute
    {

        private ILogger<CustomExceptionFilter> _logger;
        private IModelMetadataProvider _modelMetadataProvider;
        public CustomExceptionFilter(ILogger<CustomExceptionFilter> logger, IModelMetadataProvider modelMetadataProvider)
        {
            this._logger = logger;
            this._modelMetadataProvider = modelMetadataProvider;
        }
        public override void OnException(ExceptionContext context)
        {
            string msg = string.Empty;
            if (!context.ExceptionHandled)
            {
                if (context.Exception.Message.Contains("runtime"))
                {
                    msg = context.Exception.Message.Replace("runtime", "服务器异常");
                }
                else
                {
                    msg = "服务器异常,请稍后重新尝试!";
                }

                context.Result = new JsonResult(
                    new
                    {
                        code = 500,
                        msg = msg,
                        status = false
                    });
                RecodeLog(context.Exception);
            }
            base.OnException(context);
        }

        private void RecodeLog(Exception ex)
        {
            if (ex!=null)
            {
                _logger.LogError(ex.Message);
                if (ex.InnerException != null)
                {
                    RecodeLog(ex.InnerException);
                }
            }

        }
    }
}
